// 配置 CORS 中间件，允许特定来源的跨域请求访问 /api 路径
// 下的接口。
const express = require("express");
const mysql = require("mysql");
const app = express();
const jwt = require("jsonwebtoken");
const { expressjwt: expressJWT } = require("express-jwt");
const config = {
  jwtSecretKey: "jay",
  expiresIn: "80m",
};
const db = mysql.createPool({
  host: "127.0.0.1",
  user: "root",
  password: "root",
  database: "node",
});
const cors = require("cors");

// 配置 CORS 选项
const corsOptions = {
  // 允许访问的域名
  origin: "http://127.0.0.1:3000",
  optionsSuccessStatus: 200,
};

app.use(cors(corsOptions));

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(
  expressJWT({
    secret: config.jwtSecretKey, 
    algorithms: ["HS256"],
  }).unless({
    path: ["/login"], 
  })
);

app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.status(err.status).send({ code: err.status, msg: err.message });
  }
  next();
});

app.get("/info", (req, res) => {
  db.query("select * from work", (err, result) => {
    if (err) {
      return res.status(500).send({ code: 999, msg: err.message, data: null });
    }
    res.send({ code: 0, msg: "查询成功", data: result });
  });
});
app.use("/api", express.static("public"));

app.post("/login", (req, res) => {
  db.query(
    "select * from work where name = ? and password = ?",
    [req.body.name, req.body.password],
    (err, result) => {
      if (err) return res.status(500).send({ code: 999, msg: err.message });
      if (result.length === 0) {
        res.send({ code: 5000, msg: "用户名或者密码错误" });
      } else {
        const user = {
          ...result[0],
          password: "",
        };
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {
          expiresIn: config.expiresIn,
        });
        res.send({
          code: 0,
          msg: "登录成功",
          data: {
            ...user,
            token: "Bearer " + tokenStr,
          },
        });
      }
    }
  );
});

// 启动服务器
app.listen(3000, () => {
  console.log("项目启动了");
});
